package org.tinygame.herostory.cmdHandle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.tinygame.herostory.Broadcaster;
import org.tinygame.herostory.model.User;
import org.tinygame.herostory.model.UserManager;
import org.tinygame.herostory.msg.GameMsgProtocol;

public class UserEntryCmdHandle implements ICmdHandler<GameMsgProtocol.UserEntryCmd> {

    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserEntryCmd cmd) {
        if (null == ctx || null == cmd){
            return;
        }
        //获取用户Id
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (null == userId) {
            return;
        }
        User exitsUser = UserManager.getUserById(userId);
        if (null == exitsUser) {
            return;
        }
        //获取英雄形象
        String hereAvatar = exitsUser.hereAvatar;

        GameMsgProtocol.UserEntryResult.Builder resultBuilder = GameMsgProtocol.UserEntryResult.newBuilder();
        resultBuilder.setUserId(userId);
        resultBuilder.setHeroAvatar(hereAvatar);

        //所有业务流程完成后将返回的消息体构建出来
        GameMsgProtocol.UserEntryResult newResult = resultBuilder.build();
        //群发给组中的所有连接
        Broadcaster.broadcast(newResult);
    }
}
